package com.sisSaude.utils;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Locale;

public class MyDouble {
  static protected String formato = new String("###.###.##0,00");

  public static float asFloat(double valor) {
    return new Float(MyDouble.asString(valor)).floatValue();
  }

  public static String asString(double valor) {
    return Double.toString(valor);
  }

  public static String formatted(double valor) {
	DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(new Locale("pt", "BR"));
	decimalFormat.applyLocalizedPattern(formato);
	return decimalFormat.format(valor);
  }

  public static String formatted(double valor, String formato) {
	DecimalFormat decimalFormat = (DecimalFormat) DecimalFormat.getInstance(new Locale("pt", "BR"));
	decimalFormat.applyLocalizedPattern(formato);
	return decimalFormat.format(valor);
  }

  public static String unformatted(String s) {
    int    i;
    String result = "";
    if  (s != null) {
        for (i = 0; i < s.length(); i++) {
	          if      ( (s.charAt(i) >= '0') && (s.charAt(i) <= '9'))
	  	              result = result + s.charAt(i);
            else if (s.charAt(i) == ',')
                    result = result + ".";
        }
    }
    return result;
  }

  public static double rounded(double valor) {
    BigDecimal valorDecimal = new BigDecimal(valor);
    valorDecimal            = valorDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
    return valorDecimal.doubleValue();
  }

  public static double rounded(int decimais, double valor) {
    BigDecimal valorDecimal = new BigDecimal(valor);
    valorDecimal = valorDecimal.setScale(decimais, BigDecimal.ROUND_HALF_UP);
    return valorDecimal.doubleValue();
  }

  public static double fromString(String valor) {
  	return new Double(unformatted(valor)).doubleValue();
  }

  public static double fromString(int decimais, String valor) {
    return rounded(decimais, new Double(unformatted(valor)).doubleValue());
  }

  public static boolean isValidDouble(String s) {
    boolean valido;
    try {
        new Double(s).doubleValue();
        valido = true;
    }
    catch (Exception e)  {
        valido = false;
    }
    return valido;
  }

  public static double perc(double valor1, double valor2) {
	  if (valor2 == 0)
		  return 0;
	  return valor1 / valor2 * 100;
  }
}
